//
//  StatusCellPictureView.swift
//  Weibo
//
//  Created by 梁智 on 15/11/28.
//  Copyright © 2015年 lzfree. All rights reserved.
//

import UIKit
import SDWebImage

/// 照片之间的间距
private let StatusPictureViewItemMargin: CGFloat = 8

/// 可重用标示符号
private let StatusPictureCellId = "StatusPictureCellId"

/// 配图视图
class StatusCellPictureView: UICollectionView {

    // MARK: - 微博视图模型
    var viewModel: StatusViewModel? {
        didSet {
            // 自动计算大小
            sizeToFit()
            
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcViewSize()
    }
    
    // MARK: - 构造函数
    init() {
        
        let layout = UICollectionViewFlowLayout()
        
        layout.minimumInteritemSpacing = StatusPictureViewItemMargin
        layout.minimumLineSpacing = StatusPictureViewItemMargin
        
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        dataSource = self
        delegate = self
        
        // 注册可重用 id
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureCellId)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

// MARK: - 实现数据源方法
extension StatusCellPictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    /// 选中图片
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        // 测试动画转场协议函数
        photoBrowserPresentFromRect(indexPath)
        photoBrowserPresentToRect(indexPath)
        
        // 发送通知
        NSNotificationCenter.defaultCenter().postNotificationName(WBStatusSelectedPhotoNotification, object: self, userInfo: [WBStatusSelectedPhotoIndexPathKey: indexPath, WBStatusSelectedPhotoURLsKey: viewModel!.thumbnailUrls!])
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.thumbnailUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureCellId, forIndexPath: indexPath) as! StatusPictureViewCell
        
        cell.imageURL = viewModel!.thumbnailUrls![indexPath.item]
        
        return cell
    }
}


// MARK: - 照片查看器的展现协议
extension StatusCellPictureView: PhotoBrowserPresentDelegate {
    
    /// 创建一个 imageView 参与动画
    func imageViewForPresent(indexPath: NSIndexPath) -> UIImageView {
        
        let iv = UIImageView()
        
        // 1. 设置内容填充模式
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        // 2. 设置图像（缩略图的缓存）- SDWebImage 如果已经存在本地缓存，不会发起网络请求
        if let url = viewModel?.thumbnailUrls?[indexPath.item] {
            iv.sd_setImageWithURL(url)
        }
        iv.sizeToFit()
        
        return iv
    }
    
    /// 起始位置
    func photoBrowserPresentFromRect(indexPath: NSIndexPath) -> CGRect {
        
        let cell = self.cellForItemAtIndexPath(indexPath)!
        
        let rect = self.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        
        return rect
    }
    
    /// 目标位置
    func photoBrowserPresentToRect(indexPath: NSIndexPath) -> CGRect {
        
        // 根据缩略图的大小，等比例计算目标位置
        guard let key = viewModel?.thumbnailUrls?[indexPath.item].absoluteString else {
            return CGRectZero
        }
        // 从 sdwebImage 获取本地缓存图片
        guard let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) else {
            return CGRectZero
        }
        
        // 根据图像大小，计算全屏的大小
        let w = UIScreen.mainScreen().bounds.width
        let h = image.size.height * w / image.size.width
        
        // 对高度进行额外处理
        let screenHeight = UIScreen.mainScreen().bounds.height
        var y: CGFloat = 0
        if h < screenHeight {       // 图片短，垂直居中显示
            y = (screenHeight - h) * 0.5
        }
        
        let rect = CGRect(x: 0, y: y, width: w, height: h)
        
        return rect
    }
}


// MARK: - 视图大小
extension StatusCellPictureView {
    
    private func calcViewSize() -> CGSize {
        
        // 准备
        // 默认每行3张图片
        let rowCount: CGFloat = 3
        // collectionView 总宽度
        let maxWidth = UIScreen.mainScreen().bounds.width - 2 * StatusCellMargin
        // 每张图片宽度
        let itemWidth = (maxWidth - 2 * StatusPictureViewItemMargin) / rowCount
        
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        // 设置 itemSize
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        // 图片数量
        let count = viewModel?.thumbnailUrls?.count ?? 0
        
        
        // 计算开始
        if count == 0 {
            layout.itemSize = CGSize(width: 1, height: 1)
            return CGSizeZero
        }
        
        if count == 1 {
            // TODO: - 临时指定大小
            var size = CGSize(width: 150, height: 120)
            
            if let key = viewModel?.thumbnailUrls?.first?.absoluteString {
                let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
                size = image.size
            }
            // 过窄处理
            size.width = size.width < 40 ? 40 : size.width
            // 过宽处理 - 等比例缩放
            if size.width > 300 {
                let w: CGFloat = 300
                let h = size.height * w / size.width
                
                size = CGSize(width: w, height: h)
            }
            
            // 内部图片大小
            layout.itemSize = size
            
            return size
        }
        
        // 四张图片 2*2
        if count == 4 {
            let w = 2 * itemWidth + StatusPictureViewItemMargin
            
            return CGSize(width: w, height: w)
        }
        
        // 其他图片,按照九宫格来显示
        // 计算行数
        /*
        2 3
        5 6
        7 8 9
        */
        let row = CGFloat((count - 1) / Int(rowCount) + 1)
        let h = row * itemWidth + (row - 1) * StatusPictureViewItemMargin
        let w = rowCount * itemWidth + (rowCount - 1) * StatusPictureViewItemMargin
        
        return CGSize(width: w, height: h)
    }
}


// MARK: - 配图 cell
private class StatusPictureViewCell: UICollectionViewCell {
    
    var imageURL: NSURL? {
        didSet {
            iconView.sd_setImageWithURL(imageURL, placeholderImage: nil, options: [SDWebImageOptions.RetryFailed, SDWebImageOptions.RefreshCached])
        }
    }
    
    // MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(iconView)
        
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 懒加载控件
    private lazy var iconView: UIImageView = {
        let iv = UIImageView()
        
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        return iv
    }()
}
